package com.ys.controller.api.hr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ys.config.MenuId;
import com.ys.entity.hr.TbMedicalInsurance;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.hr.TbMedicalInsuranceService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/tbMedicalInsurance")
public class ApiInterTbMedicalInsuranceController {
	
//	private static final Logger logger = Logger.getLogger(ApiAdminLoginController.class);
	
	@Autowired
	private CommonApiService<TbMedicalInsurance> commonApiService;
	@Autowired
	private TbMedicalInsuranceService tbMedicalInsuranceService;
	private static final Logger logger = LoggerFactory.getLogger(ApiInterTbMedicalInsuranceController.class);

//	@RequiresPermissions("tpFbaPlanOrder:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
			@ModelAttribute TbMedicalInsurance cond
			){
		cond.setOrderby("A.Id DESC");
		return commonApiService.searchLay(cond);
	}

	/**
	 * 新增
	 */
	@RequestMapping("/toAdd")
	@ResponseBody
	public R add(HttpServletRequest request, @RequestParam Map<String, Object> params) {
		try {
			logger.info("医保管理新增传参：" + params);
			//修改
			return tbMedicalInsuranceService.add(params);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}
	/**
	 * 编辑
	 */
	@RequiresPermissions("tbMedicalInsurance:edit")
	@PostMapping("/toEdit")
	@ResponseBody
	public R edit(HttpServletRequest request,
				  @RequestParam Map<String, Object> params){
		try {
			return tbMedicalInsuranceService.edit(params);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}

	/**
	 * 弹出框
	 */
	@RequestMapping("/searchForModal")
	@ResponseBody
	public LayuiTableVoJA searchForModal(@ModelAttribute TbMedicalInsurance cond){
		//cond.addField("A.MiBase AS miBase")//医保基数
				//.addField("SUM(A.MiUnitMoonth + A.MiUnitMonth) AS medicalInsuranceByCompany")//医保（单位）/月
		cond.addField("A.MiIndividualMonth AS medicalInsuranceByPersonal");//医保（个人）/月
		cond.setStatus(1);

		LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
		//获取
		JSONArray tableVoJAData = tableVoJA.getData();
		//转换
		List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
		List<Map<String, Object>> resListNew = new ArrayList();
		resList.forEach(item-> resListNew.add(item));
		resListNew.forEach(item->{
			BigDecimal medicalInsuranceByCompany = BigDecimal.ZERO;//医保（单位）/月
			if(item.get("miUnitMoonth")!=null){
				medicalInsuranceByCompany = medicalInsuranceByCompany.add(new BigDecimal(item.get("miUnitMoonth").toString()));
			}
			if(item.get("miUnitMonth")!=null){
				medicalInsuranceByCompany = medicalInsuranceByCompany.add(new BigDecimal(item.get("miUnitMonth").toString()));
			}
			item.put("medicalInsuranceByCompany",medicalInsuranceByCompany);
		});

		JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resListNew));
		tableVoJA.setData(jsonArray);
		return tableVoJA;

	}
	/*
	 * 导出
	 */
	@RequiresPermissions("tbMedicalInsurance:export")
	@RequestMapping("/export")
	@ResponseBody
	public R export(@ModelAttribute TbMedicalInsurance cond) throws Exception{
		cond.setOrderby("A.Id DESC");

		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond.queryMap();

		List<YsCol> listField = new YsCol()
				.setMenuId(MenuId.TB_MedicalInsurance)
				.setFrontShow(YsColEnum.FrontShow.SHOW.value)
				.setOrderby("A.SortNo asc")
				.queryList();


		ExportExcelUtils<TbMedicalInsurance> util = new ExportExcelUtils<TbMedicalInsurance>(new TbMedicalInsurance());

		String toFilePath = util.exportExcel(listData, listField, "医保管理");
		UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
		return R.ok(dto.getUrl());
	}
}
